package com.chinacache.maint.workorder.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.chinacache.maint.commons.entity.BaseEntity;
import com.chinacache.maint.commons.orm.hibernate.Page;
import com.chinacache.maint.commons.util.DateUtils;
import com.chinacache.maint.commons.util.HttpUtil;
import com.chinacache.maint.commons.web.struts2.CRUDActionSupport;
import com.chinacache.maint.workorder.entity.Field;
import com.chinacache.maint.workorder.entity.FieldAttribute;
import com.chinacache.maint.workorder.entity.FieldClass;
import com.chinacache.maint.workorder.entity.FieldClassToField;
import com.chinacache.maint.workorder.entity.Flow;
import com.chinacache.maint.workorder.entity.FlowFieldAttribute;
import com.chinacache.maint.workorder.entity.FlowFieldClass;
import com.chinacache.maint.workorder.entity.WorkOrder;
import com.chinacache.maint.workorder.entity.WorkOrderStep;
import com.chinacache.maint.workorder.service.FieldAttributeManager;
import com.chinacache.maint.workorder.service.FlowFieldAttributeManager;
import com.chinacache.maint.workorder.service.FlowManager;
import com.chinacache.maint.workorder.service.WorkOrderManager;
import com.chinacache.maint.workorder.service.WorkOrderStepManager;

@SuppressWarnings("serial")
public class WorkOrderStepAction extends CRUDActionSupport<WorkOrderStep> {
	private WorkOrderStepManager workOrderStepManager;
	private WorkOrderManager workOrderManager;
	private FieldAttributeManager fieldAttributeManager;
	private FlowFieldAttributeManager flowFieldAttributeManager;
	private FlowManager flowManager;
	private WorkOrderStep entity;
	private Integer id;
	private Integer workOrderId;
	private Integer workOrderStepId;
	private Integer flowClassId;
	private Integer flowOrder;
	private Integer flowStatus;
	private Integer flowId;
	private List<WorkOrderStep> workOrderSteps = new ArrayList<WorkOrderStep>();
	private Page<WorkOrderStep> page = new Page<WorkOrderStep>();
	private Flow inputFlow = new Flow();
	private String validateString = "";

	public WorkOrderStep getEntity() {
		return entity;
	}

	public String getValidateString() {
		return validateString;
	}

	public void setValidateString(String validateString) {
		this.validateString = validateString;
	}

	Map<List, Map> view = null;

	@Override
	public String delete() throws Exception {
		workOrderStepManager.deleteWorkOrderStep(id);
		return RELOAD;
	}

	@Override
	public WorkOrderStep getModel() {
		return entity;
	}

	@Override
	public Page<WorkOrderStep> getPage() {
		return page;
	}

	@Override
	public String list() throws Exception {
		WorkOrder workOrder = workOrderManager.getWorkOrder(workOrderId);
		workOrderSteps.addAll(workOrder.getWorkOrderSteps());
		return SUCCESS;
	}

	@Override
	public void prepare() throws Exception {
		if (id == null)
			id = workOrderStepId;
		if (id != null) {
			entity = workOrderStepManager.getWorkOrderStep(id);
		} else {
			entity = new WorkOrderStep();
		}
	}

	public String view() throws Exception {
		view = new LinkedHashMap<List, Map>();
		if (flowId == null) {
			WorkOrder workOrder = workOrderManager.getWorkOrder(workOrderId);
			for (WorkOrderStep wos : workOrder.getWorkOrderSteps()) {
				id = wos.getId();
				flowId = wos.getFlow().getId();
				inputFlow = flowManager.getFlow(flowId);
				getFieldAttributeByFlowAndWorOrderStep(wos, inputFlow);
			}
		} else {
			inputFlow = flowManager.getFlow(flowId);
			getFieldAttributeByFlowAndWorOrderStep(entity, inputFlow);
		}

		return "view";
	}

	public String update() throws Exception {

		if (entity.getIsModify()!=null&&entity.getIsModify() == BaseEntity.AUDIT_NO) {
			this.msg = "数据已审核，不允许修改！";
			return list();
		}
		view = new LinkedHashMap<List, Map>();
		if (flowId == null) {
			WorkOrder workOrder = workOrderManager.getWorkOrder(workOrderId);
			for (WorkOrderStep wos : workOrder.getWorkOrderSteps()) {
				id = wos.getId();
				flowId = wos.getFlow().getId();
				inputFlow = flowManager.getFlow(flowId);
				getFieldAttributeByFlowAndWorOrderStep(wos, inputFlow);
			}
		} else {
			inputFlow = flowManager.getFlow(flowId);
			getFieldAttributeByFlowAndWorOrderStep(entity, inputFlow);
		}

		return "view";
	}

	public String audit() throws Exception {
		entity.setIsModify(BaseEntity.MODIFY_YES);
		entity.setTime(DateUtils.getCurrDate());
		entity.setUsername((String) HttpUtil.getFromSession("userName"));
		workOrderStepManager.updateWorkOrderStep(entity);
		return list();
	}

	public void getFieldAttributeByFlowAndWorOrderStep(WorkOrderStep wos,
			Flow flow) {

		Map<String, List> fas = new LinkedHashMap<String, List>();
		for (FlowFieldClass ffc : inputFlow.getFlowFieldClasss()) {

			FieldClass fieldClass = ffc.getFieldClass();

			for (FieldClassToField fctField : fieldClass.getFieldClassFields()) {
				Field field = fctField.getField();
				List<List> fasList = new ArrayList<List>();
				Set<FieldAttribute> faSet = field.getFieldAttibutes();
				List<Integer> groupIds = new ArrayList<Integer>();
				for (FieldAttribute fa : faSet) {
					if (!groupIds.contains(fa.getGroupId())) {
						groupIds.add(fa.getGroupId());
					}
				}
				for (Integer groupId : groupIds) {
					List<FieldAttribute> faByGroupIdList = fieldAttributeManager
							.getFieldAttributeByGroupId(groupId);
					for (FieldAttribute fa : faByGroupIdList) {
						fa
								.putExtendAttribute(
										"inputValue",
										flowFieldAttributeManager
												.getFlowFieldAttributeByFlowAndWorkOrderStepAndFieldAttribute(
														flowId, fa.getId(), id));
					}
					fasList.add(faByGroupIdList);
				}
				fas.put(field.getName(), fasList);
			}

		}
		List<String> infoList = new ArrayList<String>();
		infoList.add(flow.getName());
		infoList.add(wos.getUsername());
		infoList.add(wos.getTime());
		view.put(infoList, fas);
	}

	@Override
	public String save() throws Exception {
		if (workOrderStepId != null) {
			if (!(entity.getUsername()).equalsIgnoreCase((String) HttpUtil
					.getFromSession("userName"))) {
				this.msg = "您没有当前流程修改权限！";
				return update();
			}
		}
		if (flowId == null) {
			inputFlow = flowManager.getFlowByStatusAndFlowClassId(
					BaseEntity.FLOW_STATUS_START, flowClassId);
			flowId = inputFlow.getId();
		}
		Flow flow = flowManager.getFlow(flowId);
		List<FieldAttribute> allFa = new ArrayList<FieldAttribute>();
		for (FlowFieldClass ffc : flow.getFlowFieldClasss()) {
			FieldClass fieldClass = ffc.getFieldClass();
			for (FieldClassToField fctField : fieldClass.getFieldClassFields()) {
				Field field = fctField.getField();
				allFa.addAll(field.getFieldAttibutes());
			}
		}
		// WorkOrderStep wos = new WorkOrderStep();
		entity.setTime(DateUtils.getCurrDate());
		entity.setUsername((String) HttpUtil.getFromSession("userName"));
		entity.setOrder(flow.getOrder());
		entity.setFlow(flow);
		entity.setWorkOrder(workOrderManager.getWorkOrder(workOrderId));
		entity.setIsModify(BaseEntity.AUDIT_YES);
		workOrderStepManager.saveWorkOrderStep(entity);
		List<FlowFieldAttribute> ffaList = flowFieldAttributeManager
				.selectFlowFieldAttributeByWorkOrderStepId(workOrderStepId,
						flowId);
		for (FlowFieldAttribute ffa : ffaList) {
			flowFieldAttributeManager.deleteFlowFieldAttribute(ffa.getId());
		}
		Set<FlowFieldAttribute> ffaSet = new HashSet<FlowFieldAttribute>();
		List<Integer> checkBoxLink = new ArrayList<Integer>();
		for (FieldAttribute fa : allFa) {
			String value = null;
			if (fa.getCheckBoxLink() != null) {
				if (!checkBoxLink.contains(fa.getCheckBoxLink())) {

					value = HttpUtil.getHttpServletRequest().getParameter(
							fa.getCheckBoxLink().toString());
					System.out.println("value=" + value);
					System.out.println("id=" + fa.getId());
					if (value != null) {
						if (!value.equalsIgnoreCase(fa.getId().toString()))
							value = null;
						else
							checkBoxLink.add(fa.getCheckBoxLink());
					}
				}
			} else {
				value = HttpUtil.getHttpServletRequest().getParameter(
						fa.getId().toString());
			}
			if (value != null && value.length() > 0) {
				FlowFieldAttribute ffAttribute = new FlowFieldAttribute();
				ffAttribute.setValue(value);
				ffAttribute.setFlow(flow);
				ffAttribute.setWorkOrderStep(entity);
				ffAttribute.setGroupId(fa.getGroupId());
				ffAttribute.setFieldAttribute(fa);
				ffaSet.add(ffAttribute);
				flowFieldAttributeManager.saveFlowFieldAttribute(ffAttribute);
			}

		}
		return list();
	}

	public String next() throws Exception {
		if (flowId == null) {
			inputFlow = flowManager.getFlowByStatusAndFlowClassId(
					BaseEntity.FLOW_STATUS_START, flowClassId);
			flowId = inputFlow.getId();
		}
		Flow flow = flowManager.getFlow(flowId);
		List<FieldAttribute> allFa = new ArrayList<FieldAttribute>();
		for (FlowFieldClass ffc : flow.getFlowFieldClasss()) {
			FieldClass fieldClass = ffc.getFieldClass();
			for (FieldClassToField fctField : fieldClass.getFieldClassFields()) {
				Field field = fctField.getField();
				allFa.addAll(field.getFieldAttibutes());
			}
		}
		entity.setFlow(flow);
		entity.setWorkOrder(workOrderManager.getWorkOrder(workOrderId));
		entity.setTime(DateUtils.getCurrDate());
		entity.setUsername((String) HttpUtil.getFromSession("userName"));
		entity.setOrder(flow.getOrder());
		entity.setIsModify(BaseEntity.AUDIT_YES);
		workOrderStepManager.saveWorkOrderStep(entity);
		Set<FlowFieldAttribute> ffaSet = new HashSet<FlowFieldAttribute>();
		List<Integer> checkBoxLink = new ArrayList<Integer>();
		for (FieldAttribute fa : allFa) {
			String value = null;
			if (fa.getCheckBoxLink() != null) {
				if (!checkBoxLink.contains(fa.getCheckBoxLink())) {

					value = HttpUtil.getHttpServletRequest().getParameter(
							fa.getCheckBoxLink().toString());
					if (value != null) {
						if (!value.equalsIgnoreCase(fa.getId().toString()))
							value = null;
						else
							checkBoxLink.add(fa.getCheckBoxLink());
					}
				}
			} else {
				value = HttpUtil.getHttpServletRequest().getParameter(
						fa.getId().toString());
			}
			if (value != null && value.length() > 0) {
				FlowFieldAttribute ffAttribute = new FlowFieldAttribute();
				ffAttribute.setValue(value);
				ffAttribute.setFlow(flow);
				ffAttribute.setWorkOrderStep(entity);
				ffAttribute.setGroupId(fa.getGroupId());
				ffAttribute.setFieldAttribute(fa);
				ffaSet.add(ffAttribute);
				flowFieldAttributeManager.saveFlowFieldAttribute(ffAttribute);
			}

		}
		return flow();
	}

	@SuppressWarnings("unchecked")
	public String flow() throws Exception {
		if (flowStatus != null && flowStatus == BaseEntity.FLOW_STATUS_END) {
			return list();
		} else {
			WorkOrder workOrder = workOrderManager.getWorkOrder(workOrderId);
			List<WorkOrderStep> wosList = new ArrayList<WorkOrderStep>();
			wosList.addAll(workOrder.getWorkOrderSteps());
			if (workOrder.getWorkOrderSteps().size() == 0) {
				inputFlow = flowManager.getFlowByStatusAndFlowClassId(
						BaseEntity.FLOW_STATUS_START, flowClassId);
			} else {
				flowOrder = wosList.get(wosList.size() - 1).getOrder();
				inputFlow = flowManager.getFlowByOrderAndFlowClassId(flowOrder
						.intValue() + 1, flowClassId);
			}
			if (inputFlow == null) {
				return list();
			} else {
				view = new LinkedHashMap<List, Map>();

				for (FlowFieldClass ffc : inputFlow.getFlowFieldClasss()) {
					Map<String, List> fas = new LinkedHashMap<String, List>();
					FieldClass fieldClass = ffc.getFieldClass();

					for (FieldClassToField fctField : fieldClass
							.getFieldClassFields()) {
						List<List> fasList = new ArrayList<List>();
						Field field = fctField.getField();
						Set<FieldAttribute> faSet = field.getFieldAttibutes();
						List<Integer> groupIds = new ArrayList<Integer>();
						for (FieldAttribute fa : faSet) {
							if (!groupIds.contains(fa.getGroupId())) {
								groupIds.add(fa.getGroupId());
							}
						}
						for (Integer groupId : groupIds) {
							List<FieldAttribute> faByGroupIdList = fieldAttributeManager
									.getFieldAttributeByGroupId(groupId);
							for (FieldAttribute fa : faByGroupIdList) {
								if (fa.getIsMustInput() == BaseEntity.IS_MUST_INPUT_YES) {
									if (fa.getType() == BaseEntity.FIELD_TYPE_TEXT) {
										validateString += "if(isEmpty(document.getElementById("
												+ fa.getId()
												+ ").value)){\n  alert(\""
												+ fa.getName()
												+ "不能为空！\");\n document.getElementById("
												+ fa.getId()
												+ ").focus();\n return false;\n}\n";
										validateString += "if(Trim(document.getElementById("
												+ fa.getId()
												+ ").value).length>50){\n  alert(\""
												+ fa.getName()
												+ "输入长度不能大于50！\");\n document.getElementById("
												+ id
												+ ").focus();\n return false;\n}\n";
									} else if (fa.getType() == BaseEntity.FIELD_TYPE_RADIO) {
										String name = "";
										List<FieldAttribute> faByCheckBoxLinkList = fieldAttributeManager
												.getFieldAttributeByCheckBoxLink(fa
														.getCheckBoxLink());
										for (FieldAttribute fa1 : faByCheckBoxLinkList) {
											if ("".equals(name))
												name += fa1.getName();
											else
												name += "或" + fa1.getName();
										}

										validateString += "var tag=true;\n";
										validateString += "var rad = document.getElementsByName("
												+ fa.getCheckBoxLink() + ");\n";
										validateString += "for(i=0;i<rad.length;i++)\n";
										validateString += "{\n";
										validateString += "if(rad[i].checked==true)\n";
										validateString += "{\n";
										validateString += "tag=false;\n";
										validateString += "}\n";
										validateString += "}\n";
										validateString += "if(tag)\n";
										validateString += "{\n";
										validateString += "tag=\"\";\n";
										validateString += "rad=\"\"\n";
										validateString += "alert(\"" + name
												+ "没有选择！\");\n";
										validateString += "document.getElementById("
												+ fa.getCheckBoxLink()
												+ ").focus();\n";
										validateString += "return false;\n";
										validateString += "}\n";

									} else {
										validateString += "if(!document.getElementById("
												+ fa.getId()
												+ ").checked){\n  alert(\""
												+ fa.getName()
												+ "没有选择！\");\n document.getElementById("
												+ fa.getId()
												+ ").focus();\n return false;\n}\n";
									}
								}
							}
							fasList.add(faByGroupIdList);

						}
						fas.put(field.getName(), fasList);

					}
					List<String> aList = new ArrayList<String>();
					aList.add(fieldClass.getName());
					aList.add("");
					aList.add("");
					view.put(aList, fas);

				}
				flowStatus = inputFlow.getStatus();
				flowOrder = inputFlow.getOrder();
				flowId = inputFlow.getId();
				return "flow";
			}
		}
	}

	public void encapsulationJavaScript(Integer id, String name, boolean text) {
		if (text) {
			validateString += "if(isEmpty(document.getElementById(" + id
					+ ").value)){\n  alert(\"" + name
					+ "不能为空！\");\n document.getElementById(" + id
					+ ").focus();\n return false;\n}\n";
			validateString += "if(Trim(document.getElementById(" + id
					+ ").value).length>50){\n  alert(\"" + name
					+ "输入长度不能大于50！\");\n document.getElementById(" + id
					+ ").focus();\n return false;\n}\n";
		} else {
			validateString += "if(!document.getElementById(" + id
					+ ").checked){\n  alert(\"" + name
					+ "没有选择！\");\n document.getElementById(" + id
					+ ").focus();\n return false;\n}\n";
		}
	}

	public void setWorkOrderStepManager(
			WorkOrderStepManager workOrderStepManager) {
		this.workOrderStepManager = workOrderStepManager;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setWorkOrderManager(WorkOrderManager workOrderManager) {
		this.workOrderManager = workOrderManager;
	}

	public Integer getWorkOrderId() {
		return workOrderId;
	}

	public void setWorkOrderId(Integer workOrderId) {
		this.workOrderId = workOrderId;
	}

	public Integer getFlowClassId() {
		return flowClassId;
	}

	public void setFlowClassId(Integer flowClassId) {
		this.flowClassId = flowClassId;
	}

	public Integer getFlowOrder() {
		return flowOrder;
	}

	public void setFlowOrder(Integer flowOrder) {
		this.flowOrder = flowOrder;
	}

	public void setFlowManager(FlowManager flowManager) {
		this.flowManager = flowManager;
	}

	public Integer getFlowStatus() {
		return flowStatus;
	}

	public void setFlowStatus(Integer flowStatus) {
		this.flowStatus = flowStatus;
	}

	public Flow getInputFlow() {
		return inputFlow;
	}

	public void setInputFlow(Flow inputFlow) {
		this.inputFlow = inputFlow;
	}

	public void setFieldAttributeManager(
			FieldAttributeManager fieldAttributeManager) {
		this.fieldAttributeManager = fieldAttributeManager;
	}

	public Map<List, Map> getView() {
		return view;
	}

	public void setView(Map<List, Map> view) {
		this.view = view;
	}

	public Integer getFlowId() {
		return flowId;
	}

	public void setFlowId(Integer flowId) {
		this.flowId = flowId;
	}

	public List<WorkOrderStep> getWorkOrderSteps() {
		return workOrderSteps;
	}

	public void setFlowFieldAttributeManager(
			FlowFieldAttributeManager flowFieldAttributeManager) {
		this.flowFieldAttributeManager = flowFieldAttributeManager;
	}

	public Integer getWorkOrderStepId() {
		return workOrderStepId;
	}

	public void setWorkOrderStepId(Integer workOrderStepId) {
		this.workOrderStepId = workOrderStepId;
	}
}
